package com.zxq.tcp;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;


/**
 * 客户端发送请求
 * @author zhb
 *
 */
@Slf4j
public class TcpNetty implements Runnable {
    

    // 服务器的端口
    private int port;
    private ByteToMessageDecoder byteToMessageDecoder;
    public TcpNetty(Integer port, ByteToMessageDecoder byteToMessageDecoder){
        this.port = port;
        this.byteToMessageDecoder = byteToMessageDecoder;
    }

    

    @Override
    public void run() {

        EventLoopGroup bossEventLoopGroup = new NioEventLoopGroup();
        EventLoopGroup workEventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossEventLoopGroup,workEventLoopGroup)
                .channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,128)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(byteToMessageDecoder);
        try {
            log.debug("will start server");
            ChannelFuture closeFuture =  bootstrap.bind(port).sync();
            log.debug("server is closing");
            closeFuture.channel().closeFuture().sync();
            log.debug("server is closed");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossEventLoopGroup.shutdownGracefully();
            workEventLoopGroup.shutdownGracefully();
            log.debug("release event loop group");
        }

    }









}
